//
//  SubscribeService.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/2.
//

import UIKit
import StoreKit
import Foundation
import UICKeyChainStore
let kClearPaymentDataMode = false

class SubscribeService:NSObject {
    var payBlock:((Int, String, Int) -> Void)?
    var PaySuccessBlock:((String) -> Void)?
    static let shared = SubscribeService()
    override init() {
        super.init()
        let bundleIdentifier = Bundle.main.bundleIdentifier ?? "default"
        let serverName = "\(bundleIdentifier).pay.product.relate.account"
        self.keychainStore = UICKeyChainStore(service: serverName)
        self.resetVerifyCountForPaymentTransactionInfos()
        self.addTransactionObserver()
    }
    // 订单验证状态
    var isVerify: Bool = false
    // 密钥链存储，用于保存安全信息
    var keychainStore = UICKeyChainStore()
    // 锁对象，用于保证线程安全
    let lock: NSLock = NSLock()
    // 产品ID与产品信息的映射
    var idProductMap: [String: SKProduct] = [:]  // 适当替换 Any 类型，根据实际需要定义具体类型
    // 产品名称列表
    var productNameList: [String] = []
    // 支付日志记录器
    let logger: PaymentLogger = PaymentLogger()
    
    var retryLoadProductCount: Int = 0
    var redpacket: [String: Any]?
    var buyProductId: String = ""
    var donatoryAccount: String = ""
    var orderId:String = ""
    
    func doVerifyOrderId(
        orderId: String?,
        customId: Int,
        transactionId: String?,
        receipt: String?,
        extraInfo: String?) {
            
            // 构建参数字典
            let parameter: [String: Any] = [
                "type": "syn",
                "customId": customId,
                "orderId": orderId?.isEmpty ?? true ? "" : orderId!,
                "transactionReceipt": receipt?.isEmpty ?? true ? "" : receipt!,
                "transactionIdentifier": transactionId?.count ?? 0 > 0 ? transactionId! : "",
                "extraInfo": extraInfo?.isEmpty ?? true ? "" : extraInfo!
            ]
            // 调用 payBlock 回调，显示“正在提交收据…”的信息
            payBlock?(0, "正在提交收据...", 0)
            // 打印日志信息
            print("----------向服务器提交收据--------------")
            // 调用 doVerify 方法进行网络请求
            doVerify(parameter: parameter)
        }
    
    // 处理验证的方法
    func doVerify(parameter: [String: Any]) {
        guard let orderId = parameter["orderId"] as? String, let receiptData = parameter["transactionReceipt"] as? String  else {
            return
        }
        RequestService.instance.iapVerfiryWithOrderNo(orderNo: orderId, receiptData: receiptData) { [weak self] dict, code in
            guard let self = self else { return }
            if code == 200 {
                self.isVerify = false
                let transactionIdentifier = parameter["transactionIdentifier"] as? String
                let orderId = parameter["orderId"] as? String
//                RequestService.instance.getUserInfo()
                self.redpacket = nil
                self.payBlock?(1, "支付完成,感谢您的支持", 0)
                self.PaySuccessBlock?(orderId ?? "")
                XLog.d("内购", "----------向服务器提交收据成功--------------")
                //关闭交易
                self.finishATransaction(withTransactionId: transactionIdentifier)
                
                RequestService.instance.getUserInfo()
            }else {
                XLog.d("内购", "error")
                let status = dict["status"] as? String
                if let transactionIdentifier = parameter["transactionIdentifier"] as? String {
                    self.updatePaymentTransactionInfoVerifyCount(withTransactionId: transactionIdentifier)
                    if code == 2110 {
                        self.finishATransaction(withTransactionId: transactionIdentifier)
                    }
                }else {
                    self.updatePaymentOrderIdInfoVerifyCount(withOrderId: orderId)
                }
                
                // 上一个支付事务还在处理中,请稍后再试
                if code == 2102 {
                    self.startVerifyDelay10s()
                }else {
                    self.isVerify = false
                    self.startVerify()
                }
                let msg = dict["msg"] as? String
                if let msg = msg {
                    self.payBlock?(-1, msg, code)
                }else {
                    if code == 500 {
                        self.payBlock?(-1, "服务器验证出小差，可下拉刷新重新恢复订单流程！", code)
                    }else {
                        XLog.d("其他错误", dict)
                    }
                }
            }
            
        } failureClosure: { error in
            self.isVerify = false
            let code = error.responseCode ?? 0
            XLog.d("内购", error.errorDescription ?? "")
            self.payBlock?(-1, "network", code)
        }
    }
    
    // 延迟 10 秒后重新开始验证的方法
    func startVerifyDelay10s() {
        // 使用 GCD 的 dispatch_after 方法来实现延迟
        DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [weak self] in
            // 使用 [weak self] 来避免闭包中的强引用循环
            guard let self = self else { return }
            self.isVerify = false  // 将 isVerify 置为 NO
            self.startVerify()    // 调用 startVerify 方法重新开始验证
        }
    }
    
    // 购买产品的方法
    func buyProducts(productId: String, allProductIds: [String]) {
        // 获取当前用户
        guard let account = Appearance.shared.accoutModel else {
            // 如果用户未登录，则调用 payBlock 并返回
            payBlock?(-1, "请登录后再购买", 0)
            return
        }
        // 检查设备是否允许内购
        guard SKPaymentQueue.canMakePayments() else {
            // 如果设备不允许内购，则调用 payBlock 并返回
            payBlock?(-1, "设备不允许内购", 0)
            return
        }
        // 重置重试加载产品次数
        retryLoadProductCount = 0
        // 重置红包数据
        redpacket = nil
        // 设置即将购买的产品 ID
        buyProductId = productId
        // 设置捐赠账号
        donatoryAccount = ""
        // 设置所有产品的 ID 列表
        productNameList = allProductIds
        // 从产品映射中获取目标产品
        if let product = idProductMap[productId] {
            // 如果产品已存在，直接开始支付
            doPayWithProduct(product: product)
        } else {
            // 如果产品不存在，请求产品数据
            requestProductData(productIds: allProductIds)
        }
    }
    
    // 处理支付请求的方法，通过 SKProduct 对象进行支付
    func doPayWithProduct(product: SKProduct?) {
        guard let product = product  else { return }
        // 调用内部方法处理订单请求，传入产品对象，产品 ID 为空
        doRequestOrderIdForProduct(product: product, productId: nil)
    }
    
    // 处理支付请求的方法，通过产品 ID 进行支付
    func doPayWithProductId(productId: String) {
        // 调用内部方法处理订单请求，产品对象为空，传入产品 ID
        doRequestOrderIdForProduct(product: nil, productId: productId)
    }
    
    // 处理订单请求的方法
    func doRequestOrderIdForProduct(product: SKProduct?, productId: String?) {
        // 如果 buyProductId 为空，说明 SKProductsRequestDelegate 的回调期间，重启了应用，导致 buyProductId 被清空
        if buyProductId.isEmpty {
            redpacket = nil
            // 处理 buyProductId 为空的情况
            payBlock?(-2, "订单信息为空", 0)
            return
        }
        // 获取当前用户
        guard let account = Appearance.shared.accoutModel else {
            // 如果用户未登录，调用 payBlock 返回错误信息
            payBlock?(-1, "请登录后再购买", 0)
            return
        }
        // 创建订单请求参数
        var dict: [String: Any] = [
            "productIdentifier": buyProductId,
            "accountId": "\(account.userId ?? 0)",
            "type": "syn",
            "donatoryAccount": donatoryAccount
        ]
        if let redpacket = redpacket {
            dict["redpacket"] = redpacket
        }
        // 调用 payBlock 返回正在创建订单的状态
        payBlock?(0, "正在创建订单...", 0)
        // 进行订单请求
        RequestService.instance.iapCreateOrder(productId: self.buyProductId) { dict, code in
            if let orderId = dict["order_no"] as? String {
                self.starPayForProduct(product: product, productId: productId, withOrderId: orderId)
            }else {
                self.redpacket = nil
                self.payBlock?(-1, "创建订单失败", 0)
            }
        } failureClosure: { error in
            XLog.d("", "网络错误")
            self.payBlock?(-1, "创建订单失败!", 1002)
        }
    }
    
    // 处理支付请求的方法
    func starPayForProduct(product: SKProduct?, productId: String?, withOrderId orderId: String) {
        // 保存订单 ID
        self.orderId = orderId
        // 创建 SKMutablePayment 对象
        var payment: SKMutablePayment?
        if let product = product {
            payment = SKMutablePayment(product: product)
        }
        // 如果 payment 为空，返回错误信息
        if payment == nil {
            payBlock?(-2, "支付失败", 0)
            return
        }
        // 调用 payBlock 传递支付状态
        payBlock?(0, "正在支付...", 0)
        // 保存支付信息
        savePayInfo(orderId: self.orderId, recipient: self.donatoryAccount, productId: self.buyProductId)
        let account = Appearance.shared.accoutModel
        savePayInfoProductId(productId: self.buyProductId, relateAccountId: account?.userId ?? 0)
        // 设置 payment 的 applicationUsername
        payment?.applicationUsername = self.orderId
        // 发送购买请求
        XLog.d("", "---------发送购买请求------------")
        
        SKPaymentQueue.default().add(payment!)
    }
    
    // 请求产品数据的方法
    func requestProductData(productIds: [String]) {
        // 打印日志，表示正在请求产品信息
        XLog.d("---------请求对应的产品信息------------")
        // 调用 payBlock，提示用户正在连接苹果服务器
        if let payBlock = payBlock {
            payBlock(0, "正在连接苹果服务器...", 0)
        }
        // 将产品标识符数组转换为 NSSet 对象
        let nsSet = Set(productIds)
        // 创建 SKProductsRequest 对象
        let request = SKProductsRequest(productIdentifiers: nsSet)
        // 设置代理为当前对象
        request.delegate = self
        // 启动请求
        request.start()
    }
    
    //恢复购买
    func resetVerifyCountForPaymentTransactionInfos() {
        lock.lock()
        defer {
            lock.unlock()
        }
        let transactionInfos = SqlManager.shared.filter(from: PaymentTransactionInfo.self) ?? []
        for i in 0..<transactionInfos.count {
            var info = transactionInfos[i]
            if !info.isTransactionValidFromService {  // 检查交易是否从服务端无效
                info.modelVerifyCount = 0  // 将验证计数重置为 0
                SqlManager.shared.update(on: [PaymentTransactionInfo.Properties.modelVerifyCount], with: info, where: PaymentTransactionInfo.Properties.orderId == info.orderId ?? "")
            }
        }
        if transactionInfos.count > 0 {
            self.addTransactionObserver()
        }
    }
    
    // 添加交易观察者
    func addTransactionObserver() {
        // 获取 SKPaymentQueue 的默认实例
        let paymentQueue = SKPaymentQueue.default()
        // 添加当前对象为交易观察者
        paymentQueue.add(self)
        print("已添加交易观察者")
    }
    
    // 移除交易观察者
    func removeTransactionObserver() {
        // 获取 SKPaymentQueue 的默认实例
        let paymentQueue = SKPaymentQueue.default()
        // 从交易队列中移除当前对象作为观察者
        paymentQueue.remove(self)
        print("已移除交易观察者")
    }
    
    // 刷新收据数据（如果需要的话）
    func refreshTransactionReceiptDataIfNeed() {
        // 获取当前设备上的交易收据数据
        if let transactionReceiptData = fetchTransactionReceiptDataInCurrentDevice(), transactionReceiptData.count > 0 {
            // 如果收据数据存在，则启动验证
            startVerify()
        }
    }
    
    // 完成交易的逻辑
    private func completeTransaction(_ transaction: SKPaymentTransaction) {
        XLog.d("-----completeTransaction--------") // 打印完成交易的信息
        let productIdentifier = transaction.payment.productIdentifier // 获取产品标识符
        let orderId = transaction.payment.applicationUsername // 获取订单 ID
        // 更新支付信息
        updatePayInfo(orderId: orderId, transactionId: transaction.transactionIdentifier)
        // 如果需要，保存支付交易信息
        savePaymentTransactionInfoIfNeed(transaction: transaction)
        // 获取当前设备的收据数据
        if let receipt = fetchTransactionReceiptDataInCurrentDevice() {
            // 如果有收据数据，开始验证
            startVerify()
        } else {
            // 找不到收据，直接提示
            self.payBlock?(-1, "查询不到收据，请完全关闭 App 再重新进入看看是否到帐", 0)
            // 记录日志到服务器
            if let orderId = orderId {
                self.logger.submitLogger(withOrderId: orderId, receiptData: "")
                XLog.d("SKPaymentTransactionStatePurchased", "苹果返回成功，但查询不到收据，等刷新到收据后提交完成交易;")
            } else {
                self.logger.submitLogger(withOrderId: orderId, receiptData: "")
                XLog.d("SKPaymentTransactionStatePurchased", " 晕，可能掉单了。苹果返回成功，但查询不到绑定的订单，同时收据为空。")
            }
        }
    }
    
    func startVerify() {
        // 如果正在验证中，则直接返回
        if self.isVerify {
            XLog.d("", "正在验证")
            return
        }
        //        // 网络检查, 避免没有网络的情况下页一直发送验证请求
        //        let networkReachabilityStatus = self.networkReachabilityManager.networkReachabilityStatus
        //        let isNetworkEnable = (networkReachabilityStatus == .reachableViaWWAN || networkReachabilityStatus == .reachableViaWiFi)
        //        if !isNetworkEnable {
        //            return
        //        }
        // 获取当前设备的收据数据
        guard let receipt = fetchTransactionReceiptDataInCurrentDevice() else {
            return
        }
        // 获取需要验证的支付交易信息列表
        let list = getShouldVerifyPaymentTransactionInfos()
        if let list = list, !list.isEmpty {
            if self.isVerify {
                return
            }
            self.isVerify = true
            // 获取列表中的第一个交易信息
            let info = list.first!
            if info.orderId?.count ?? 0 <= 0  {
                // 如果 orderId 为空，直接完成交易
                finishATransaction(withTransactionId: info.transactionId ?? "")
                deletePaymentTransactionInfoAfterVerify(transactionId: info.transactionId)
                self.isVerify = false
                // 10 秒后重新开始验证
                DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
                    self.startVerify()
                }
                return
            }
            // 将收据数据转换为 Base64 编码的字符串
            let receiptString = receipt.base64EncodedString(options: [])
            if info.modelVerifyCount ?? 0 > 0 {  // 说明是重新验证
                var intervalDelta = Double(info.modelVerifyCount ?? 0) * 10
                if intervalDelta > 60 {
                    intervalDelta = 60
                }
                // 延迟一段时间后进行验证
                DispatchQueue.main.asyncAfter(deadline: .now() + intervalDelta) {
                    XLog.d("===> 开始校对事务 \(info.transactionId ?? ""), 重试次数: \(info.modelVerifyCount ?? 0)")
                    self.doVerifyOrderId(orderId: info.orderId,
                                         customId: info.accountId ?? 0,
                                         transactionId: info.transactionId,
                                         receipt: receiptString,
                                         extraInfo: "交易完成")
                }
            } else {
                XLog.d("===> 开始校对事务 \(info.transactionId ?? ""), 重试次数: \(info.modelVerifyCount ?? 0)")
                self.doVerifyOrderId(orderId: info.orderId,
                                     customId: info.accountId ?? 0,
                                     transactionId: info.transactionId,
                                     receipt: receiptString,
                                     extraInfo: "交易完成")
            }
        }
    }
    
    func failedTransaction(transaction: SKPaymentTransaction) {
        XLog.d("购买失败")
        // 获取错误信息
        let error = transaction.error as? SKError
        let orderId = transaction.payment.applicationUsername
        let productIdentifier = transaction.payment.productIdentifier
        // 更新支付信息
        updatePayInfo(orderId: orderId, transactionId: transaction.transactionIdentifier)
        if error?.code != SKError.paymentCancelled.rawValue {
            if let payBlock = self.payBlock {
                var msg: String? = nil
                if let errorDesc = error?.localizedDescription {
                    // 根据不同的错误代码生成不同的错误信息
                    if errorDesc.contains("Cannot connect to iTunes Store") {
                        msg = "无法连接 iTunes Store 充值，请换网络重试"
                    } else if error?.code == SKError.unknown.rawValue {
                        msg = "充值遇到未知错误(SKErrorUnknown)，请稍候重试\n\(errorDesc)"
                    } else if error?.code == SKError.clientInvalid.rawValue {
                        msg = "设备不允许处理支付事务(SKErrorClientInvalid)\n\(errorDesc)"
                    } else if error?.code == SKError.paymentInvalid.rawValue {
                        msg = "无效支付事务(SKErrorPaymentInvalid)\n\(errorDesc)"
                    } else if error?.code == SKError.paymentNotAllowed.rawValue {
                        msg = "设备不允许支付(SKErrorPaymentNotAllowed)\n\(errorDesc)"
                    } else if error?.code == SKError.storeProductNotAvailable.rawValue {
                        msg = "产品在您的 Apple Id 所在地区无效，请换个 Apple Id 再试\n\(errorDesc)"
                    } else if #available(iOS 9.3, *), error?.code == SKError.cloudServicePermissionDenied.rawValue {
                        msg = "不被允许访问 Apple 云服务信息\n\(errorDesc)"
                    } else if #available(iOS 9.3, *), error?.code == SKError.cloudServiceNetworkConnectionFailed.rawValue {
                        msg = "无法连接 iTunes Store 充值，请换网络重试\n\(errorDesc)"
                    } else if #available(iOS 10.3, *), error?.code == SKError.cloudServiceRevoked.rawValue {
                        msg = "用户取消访问 Apple 云服务的授权\n\(errorDesc)"
                    } else if #available(iOS 12.2, *) {
                        if error?.code == SKError.privacyAcknowledgementRequired.rawValue {
                            // 用户需要接受苹果的隐私政策
                        } else if error?.code == SKError.unauthorizedRequestData.rawValue {
                            // 应用尝试使用 SKPayment 的 requestData 属性，但没有适当的权限
                        } else if error?.code == SKError.invalidOfferIdentifier.rawValue {
                            // 指定的订阅优惠标识符无效
                        } else if error?.code == SKError.invalidSignature.rawValue {
                            // 提供的加密签名无效
                        } else if error?.code == SKError.missingOfferParams.rawValue {
                            // SKPaymentDiscount 中缺少一个或多个参数
                        } else if error?.code == SKError.invalidOfferPrice.rawValue {
                            // 选定优惠的价格无效（例如低于当前的基础订阅价格）
                        }
                    }
                    // 如果没有匹配到特定的错误信息，则使用默认的错误信息
                    if msg == nil {
                        msg = "充值遇到错误，请稍候再试 (\(error?.code ?? SKError.unknown))\n\(errorDesc)"
                    }
                    // 调用 payBlock 回调，传递错误信息
                    payBlock(-1, msg ?? "", 0)
                }
            }
            // 获取收据数据并转换为字符串
            let receiptData = fetchTransactionReceiptDataInCurrentDevice()
            let receiptString = receiptData != nil ? String(data: receiptData!, encoding: .utf8) ?? "" : ""
            XLog.d("getSKErrorDescription:", error?.code.rawValue)
            // 记录支付生产日志
            self.logger.submitLogger(withOrderId: orderId, receiptData: receiptString)
        } else {
            // 用户主动取消支付
            self.payBlock?(-2, "您取消了支付", 0)
        }
        // 完成交易
        finishATransaction(transaction)
    }
    
    func finishATransaction(_ transaction: SKPaymentTransaction?) {
        // 如果交易为空，直接返回
        guard let transaction = transaction else {
            return
        }
        // 不能完成一个正在交易的订单
        if transaction.transactionState == .purchasing {
            return
        }
        // 完成交易
        SKPaymentQueue.default().finishTransaction(transaction)
    }
    
    func finishATransaction(withTransactionId transactionId: String?) {
        // 如果 transactionId 为空，直接返回
        guard let transactionId = transactionId, transactionId.count > 0 else {
            return
        }
        // 获取当前队列中的所有待处理交易
        let transactionsWaitingForVerify = SKPaymentQueue.default().transactions
        // 查找指定的交易
        var targetTransaction: SKPaymentTransaction?
        for transaction in transactionsWaitingForVerify {
            if transaction.transactionIdentifier == transactionId {
                targetTransaction = transaction
                break
            }
        }
        // 如果未找到目标交易
        if targetTransaction == nil {
            XLog.d("如果未找到目标交易", "进来了")
            // 记录这笔已经完成的订单的状态，以便之后处理
            // 天啦噜, 又出现订单在后台验证成功, 但是从 IAP 的未完成订单里取不到这比交易的错误
            updatePayInfoTransaction(transactionId: transactionId)
        } else {
            XLog.d("删除验证后的支付交易信息", "进来了")
            // 删除验证后的支付交易信息
            deletePaymentTransactionInfoAfterVerify(transactionId: transactionId)
            // 完成交易
            finishATransaction(targetTransaction!)
        }
    }
    
    func checkUnfinishedTransactionInSandbox() {
        startVerify()
    }
    
    func fetchTransactionReceiptDataInCurrentDevice() -> Data? {
        // 获取应用的收据 URL
        let appStoreReceiptURL = Bundle.main.appStoreReceiptURL
        // 从收据 URL 读取收据数据
        guard let data = try? Data(contentsOf: appStoreReceiptURL!) else {
            print("=========>>>>  appStoreReceipt Data is nil")
            // 如果收据数据为空且有未完成的交易，创建一个刷新收据请求
            if hasUnFinishTransactions() {
                let request = SKReceiptRefreshRequest()
                request.delegate = self
                request.start()
            }
            return nil
        }
        return data
    }
    
    func hasUnFinishTransactions() -> Bool {
        // 调用 getUnFinishPaymentTransactionInfos 方法获取未完成的交易信息列表
        let list = getUnFinishPaymentTransactionInfos()
        // 如果列表不为空且包含至少一个元素，则返回 true，表示存在未完成的交易
        return list.count > 0
    }
    
    func getUnFinishPaymentTransactionInfos() -> [PaymentTransactionInfo] {
        // 锁定当前线程，保证线程安全
        lock.lock()
        defer { lock.unlock() } // 确保解锁，无论方法是否成功执行
        // 从 PaymentRepository 中获取所有支付事务信息
        let list = SqlManager.shared.filter(from: PaymentTransactionInfo.self) ?? []
        // 筛选出所有未完成的交易信息
        let result = list.filter { !$0.isTransactionValidFromService }
        return result
    }
    
    func getShouldVerifyPaymentTransactionInfos() -> [PaymentTransactionInfo]? {
        // 锁定当前线程，保证线程安全
        lock.lock()
        defer { lock.unlock() } // 确保解锁，无论方法是否成功执行
        var result = [PaymentTransactionInfo]()  // 所有应该验证的订单
        var list = SqlManager.shared.filter(from: PaymentTransactionInfo.self) ?? []
        let account = Appearance.shared.accoutModel
        for i in 0..<list.count {
            if !list[i].isTransactionValidFromService && list[i].modelVerifyCount ?? 0 < 10 {
                // 删除重装后拿到的收据，且 transaction.payment.applicationUsername 是 nil
                if list[i].accountId == 0 && list[i].orderId == nil {
                    var aid = getPayInfoAccountIdRelateProductId(productId: list[i].productId ?? "")
                    if aid == 0 {
                        aid = account?.userId ?? 0
                    }
                    if aid > 0 {
                        list[i].accountId = aid
                        result.append(list[i])
                    }
                } else {
                    result.append(list[i])
                }
            }
        }
        var listNeverVerify = [PaymentTransactionInfo]()
        var listModelsRetry = [PaymentTransactionInfo]()
        for model in result {
            if model.modelVerifyCount == 0 {
                listNeverVerify.append(model)
            } else {
                listModelsRetry.append(model)
            }
        }
        // 日期降序排序. 新支付的，优先校对
        listNeverVerify.sort {
            ($0.transactionDate ?? Date.distantPast) > ($1.transactionDate ?? Date.distantPast)
        }
        // 验证次数少的排前面.
        listModelsRetry.sort { $0.modelVerifyCount ?? 0 < $1.modelVerifyCount ?? 0 }
        var last = [PaymentTransactionInfo]()
        last.append(contentsOf: listNeverVerify)
        last.append(contentsOf: listModelsRetry)
        return last
    }
    
    deinit {
        SKPaymentQueue.default().remove(self)
    }
}
extension SubscribeService: SKRequestDelegate, SKPaymentTransactionObserver, SKProductsRequestDelegate  {
    // 处理产品请求的响应
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        // 如果产品列表为空
        if response.products.isEmpty {
            // 重试三次
            if retryLoadProductCount < 3 {
                retryLoadProductCount += 1
                requestProductData(productIds: productNameList) // 重新请求产品数据
                return
            }
        } else {
            // 将收到的产品数据保存到 idProductMap 中
            for product in response.products {
                idProductMap[product.productIdentifier] = product
            }
        }
        // 从 idProductMap 中获取要购买的产品
        let product = idProductMap[buyProductId]
        if product == nil {
            self.logger.submitLogger(withOrderId: self.orderId, receiptData: "")
            XLog.d("内购", "向苹果验证产品时，返回产品列表为空，验证不了产品信息")
            doPayWithProductId(productId: buyProductId)
        } else {
            // 如果找到产品，进行支付
            doPayWithProduct(product: product)
        }
    }
    
    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        print("-----paymentQueue--------") // 打印交易队列信息
        for transaction in transactions {
            switch transaction.transactionState {
            case .purchasing: // 商品添加进列表
                XLog.d("-----商品添加进列表 --------")
            case .purchased: // 交易完成
                XLog.d("-----交易完成 --------")
//                if kClearPaymentDataMode {
//                    // 如果是测试模式，直接完成交易
//                    finishATransaction(transaction)
//                } else {
//                    // 正常模式下，完成交易
//                    completeTransaction(transaction)
//                }
                completeTransaction(transaction)
            case .failed: // 交易失败
                XLog.d("-----交易失败 --------")
                failedTransaction(transaction: transaction)
            case .restored: // 已经购买过该商品
                // 对于消耗型商品，我们不处理此状态
                XLog.d("-----已经购买过该商品 --------")
                completeTransaction(transaction)
            case .deferred: // 延后处理，家长模式，需要授权
                XLog.d("----- 延后处理，家长模式，需要授权 --------")
            @unknown default:
                // 处理未知状态
                break
            }
        }
    }
    
    func request(_ request: SKRequest, didFailWithError error: Error) {
        XLog.d("-------弹出错误信息----------")
        // 检查请求是否为 SKReceiptRefreshRequest 类型
        if let receiptRefreshRequest = request as? SKReceiptRefreshRequest {
            // 获取收据的属性
            let receiptProperties = receiptRefreshRequest.receiptProperties ?? [:]
            let orderId = receiptProperties["orderId"] as? String ?? ""
            if !orderId.isEmpty {
                let transactionIdentifier = receiptProperties["transactionIdentifier"] as? String ?? ""
                let productIdentifier = receiptProperties["productIdentifier"] as? String ?? ""
                // 记录日志
                self.logger.submitLogger(withOrderId: orderId, receiptData: "")
            }
            // 调用回调函数
            payBlock?(-1, "刷新收据不成功", 0)
        } else {
            // 处理其他类型的请求失败情况
            payBlock?(-1, error.localizedDescription, 0)
        }
    }
    
    // 请求完成后的回调方法
    func requestDidFinish(_ request: SKRequest) {
        XLog.d("----------反馈信息结束--------------")
        // 如果请求是 SKReceiptRefreshRequest 类型，则刷新交易收据数据
        if request is SKReceiptRefreshRequest {
            refreshTransactionReceiptDataIfNeed()
        }
    }
}

//验证订单
class PaymentLogger {
    private let disposeBag = DisposeBag()  // RxSwift 的 DisposeBag 用于管理订阅的生命周期
    func submitLogger(withOrderId orderId: String?, receiptData: String?) {
        guard let orderId = orderId, let receiptData = receiptData  else {
            return
        }   
        RequestService.instance.iapVerfiryWithOrderNo(orderNo: orderId , receiptData: receiptData) { dict, code in
            if code == 200 {
                XLog.d("内购", "submit payment log success")
            }else {
                XLog.d("内购", "submit payment log fail")
            }
        } failureClosure: { error in
            XLog.d("内购", "submit payment log fail")
        }
    }
}

struct PaymentTransactionInfo: TableObject {
    static var tableName: String = "PaymentTransactionInfo"
    /// 订单 id.
    var orderId: String?
    /// 用户 id.
    var accountId: Int?
    /// 受赠者昵称.
    var recipient: String?
    /// 交易时间(添加到交易队列时的时间).
    var transactionDate: Date?
    /// 商品 id.
    var productId: String?
    /// 事务 ID.
    var transactionId: String?
    var md5:String?
    var modelVerifyCount:Int?
    var isTransactionValidFromService:Bool = false
    enum CodingKeys: String, CodingTableKey {
        typealias Root = PaymentTransactionInfo
        static let objectRelationalMapping = TableBinding(CodingKeys.self)
        case orderId
        case accountId
        case recipient
        case transactionDate
        case productId
        case transactionId
        case md5
        case modelVerifyCount
        case isTransactionValidFromService
        
        static var columnConstraintBindings: [CodingKeys: ColumnConstraintBinding]? {
            return [
                orderId: ColumnConstraintBinding(isAutoIncrement: false)
            ]
        }
    }
}
